package com.tb.async;

import com.tb.util.MyConstant;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

import javax.mail.internet.MimeMessage;
import java.util.ResourceBundle;

public class MailTask implements Runnable {

	private String code;
	private String email;
	private JavaMailSender javaMailSender;
	private int operation;

	public MailTask(String code, String email, JavaMailSender javaMailSender, int operation) {
		this.code = code;
		this.email = email;
		this.javaMailSender = javaMailSender;
		this.operation = operation;
	}

	@Override
	public void run() {
		javaMailSender.send(new MimeMessagePreparator() {
			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				System.out.println("开始发邮件...");
				MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
				mimeMessageHelper.setFrom(ResourceBundle.getBundle("db").getString("mail.username"));
				mimeMessageHelper.setTo(email);
				mimeMessageHelper.setSubject("【法律援助社区】");
				StringBuilder sb = new StringBuilder();
				sb.append("<html><head></head><body>");

				if (operation == MyConstant.MAIL_ACTIVATE) {
					sb.append("你好，<br>");
					sb.append("欢迎加入【法律援助社区】<br>");
					sb.append("<a href=" + MyConstant.DOMAIN_NAME + "activateUser?userId=").append(code).append(">");
					sb.append("点击激活你的账号，如若你没有注册账号，请无视</a></body>");
				} else if (operation == MyConstant.MAIL_CHANGE_PASSWORD){
					sb.append("温馨提示：你刚刚修改了你在【法律援助社区】的登陆密码。<br>");
					sb.append("</body>");
				}

				mimeMessageHelper.setText(sb.toString(), true);

				System.out.println("结束发邮件...");
			}
		});
	}
}
